#!/usr/bin/env python3
"""Check edges for a specific node in both NetworkX and Neo4j"""

import pickle
import networkx as nx
from neo4j import GraphDatabase

# Load the original graph
print("Loading original graph...")
with open('business-payout.pkl', 'rb') as f:
    G = pickle.load(f)

target_node = 'business-payout-biz/src/main/java/com/pingpongx/business/payout/biz/service/core/OrderTemplate.java'

# Check in NetworkX graph
print(f"\n=== NetworkX Graph Analysis for {target_node} ===")

if target_node in G:
    # Outgoing edges (where node is source)
    out_edges = list(G.out_edges(target_node, data=True))
    print(f"Outgoing edges: {len(out_edges)}")

    # Incoming edges (where node is target)
    in_edges = list(G.in_edges(target_node, data=True))
    print(f"Incoming edges: {len(in_edges)}")

    # Total degree
    print(f"Total degree: {G.degree(target_node)}")

    # Group outgoing edges by type
    out_edge_types = {}
    for source, target, data in out_edges:
        edge_type = data.get('type', 'unknown')
        if edge_type not in out_edge_types:
            out_edge_types[edge_type] = []
        out_edge_types[edge_type].append(target)

    print("\nOutgoing edges by type:")
    for edge_type, targets in out_edge_types.items():
        print(f"  {edge_type}: {len(targets)} edges")
        # Show first 5 targets as examples
        for i, t in enumerate(targets[:5]):
            print(f"    -> {t}")
        if len(targets) > 5:
            print(f"    ... and {len(targets)-5} more")
else:
    print(f"Node {target_node} not found in graph!")

# Check in Neo4j
print(f"\n=== Neo4j Database Analysis ===")

driver = GraphDatabase.driver("bolt://localhost:5018", auth=("neo4j", "neo4j123"))

with driver.session() as session:
    # Check if node exists
    result = session.run("""
        MATCH (n:Node {id: $node_id})
        RETURN n.id, n.type, n.degree
    """, node_id=target_node)

    node_info = result.single()
    if node_info:
        print(f"Node found: {node_info['n.id']}")
        print(f"Type: {node_info['n.type']}")
        print(f"Degree property: {node_info['n.degree']}")

        # Count DEPENDS_ON relationships
        result = session.run("""
            MATCH (source:Node {id: $node_id})-[r:DEPENDS_ON]->(target)
            RETURN count(r) as count
        """, node_id=target_node)
        depends_count = result.single()['count']
        print(f"\nOutgoing DEPENDS_ON relationships: {depends_count}")

        # Count by relationship type
        result = session.run("""
            MATCH (source:Node {id: $node_id})-[r]->(target)
            RETURN type(r) as relType, count(r) as count
            ORDER BY count DESC
        """, node_id=target_node)

        print("\nOutgoing relationships by type:")
        for record in result:
            print(f"  {record['relType']}: {record['count']}")

        # Total outgoing
        result = session.run("""
            MATCH (source:Node {id: $node_id})-[r]->(target)
            RETURN count(r) as count
        """, node_id=target_node)
        total_out = result.single()['count']
        print(f"\nTotal outgoing relationships: {total_out}")

        # Check for duplicates
        result = session.run("""
            MATCH (source:Node {id: $node_id})-[r:DEPENDS_ON]->(target)
            RETURN target.id, count(r) as count
            ORDER BY count DESC
            LIMIT 10
        """, node_id=target_node)

        print("\nChecking for duplicate DEPENDS_ON edges to same target:")
        duplicates_found = False
        for record in result:
            if record['count'] > 1:
                duplicates_found = True
                print(f"  {record['count']} edges to: {record['target.id']}")

        if not duplicates_found:
            print("  No duplicates found")
    else:
        print(f"Node {target_node} not found in Neo4j!")

driver.close()

print("\n=== Summary ===")
print("The discrepancy is likely because:")
print("1. Each edge was imported as DEPENDS_ON relationship")
print("2. Then additional specific relationships (CONTAINS, IMPORTS, etc.) were created")
print("3. This doubled the number of relationships in Neo4j")